package models

import (
	"chat/utils"

	"gorm.io/gorm"
)

// 群信息
type GroupBasic struct {
	gorm.Model
	Name      string `json:"group_name" gorm:"群名"`
	OwnerId   uint   `json:"owner_id" gorm:"群主ID"`
	OwnerName string `json:"owner_name" gorm:"群主名称"`
	Icon      string `json:"icon" gorm:"群头像"`

	// 1: group is deleted, 2: Group normal use
	Type int    `json:"type" gorm:"群类型 deleted or use"`
	Desc string `json:"desc"  gorm:"群描述"`
}

type Group struct {
	GroupBasic
	Users []string `json:"users"`
}

func (table *GroupBasic) TableName() string {
	return "group_basic"
}

func CreateGroup(group *Group) (Group, error) {
	var groupItem Group
	utils.Mysql.Table("group_basic").Create(&group)
	err := utils.Mysql.Table("group_basic").Where("id = ?", group.ID).First(&groupItem).Error
	return groupItem, err
}

func removalG(users []*GroupBasic) []*GroupBasic {
	result := make([]*GroupBasic, 0)
	uniqueMap := make(map[string]struct{}) // 存放唯一值的 map
	for _, user := range users {
		if _, ok := uniqueMap[user.Name]; !ok {
			uniqueMap[user.Name] = struct{}{}
			result = append(result, user)
		}
	}
	return result
}

func FindNewGroup(name string) ([]*GroupBasic, error) {
	names := make([]*GroupBasic, 0)
	if err := utils.Mysql.Table("group_basic").Where("name LIKE ?", "%"+name+"%").Find(&names).Error; err != nil {
		return nil, err
	}
	groupIds := make([]*GroupBasic, 0)
	if err := utils.Mysql.Table("group_basic").Where("ID LIKE ?", "%"+name+"%").Find(&groupIds).Error; err != nil {
		return nil, err
	}
	data := append(names, groupIds...)
	res := removalG(data)
	return res, nil
}

type GroupUsers struct {
	UserBasic
	Owner uint `json:"owner"`
}

func FindGroupUsers(ID uint) ([]*UserBasic, error) {
	users := make([]*UserBasic, 0)
	subQuery := utils.Mysql.Table("contact_basic").
		Select("owner_id").
		Joins("JOIN user_basic ON user_basic.id = contact_basic.owner_id").
		Where("target_id = ? AND contact_basic.type = 2 and contact_basic.deleted_at IS NULL", ID)

	if err := utils.Mysql.Table("user_basic").
		Where("id IN (?) ", subQuery).
		Find(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}

func DissolveGroupUsers(group_id string, user_id string, owner string) error {
	if owner == "false" {
		return utils.Mysql.Table("contact_basic").Where("type = 2 and  owner_id = ? and target_id = ?", group_id, user_id).Delete(&Contact{}).Error

	} else if owner == "true" {
		return utils.Mysql.Table("contact_basic").Where("type = 2 and target_id = ?", group_id).Delete(&Contact{}).Error
	}
	return nil
}
